package com.jsyso.jsyso.spring.jdbc;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

import com.jsyso.jsyso.lang.JStringUtils;
import com.jsyso.jsyso.util.JsMap;

/**
 * spring-jdbc JsMap映射器
 * @author janjan, xujian_jason@163.com
 *
 */
public class JsMapRowMapper implements RowMapper<JsMap>  {

	// 表分隔符
	private char separator;
	// 是否开启驼峰命名
	private boolean openCamelCase;
	
	public JsMapRowMapper() {
		this(true, JStringUtils.DEFAULT_CAMEL_SEPARATOR);
	}
	
	public JsMapRowMapper(boolean openCamelCase, char separator) {
		this.openCamelCase = openCamelCase;
		this.separator = separator;
	}
	
	@Override
	public JsMap mapRow(ResultSet rs, int rowNum) throws SQLException {
		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();
		JsMap jsMap = JsMap.create(columnCount);
		for (int i = 1; i <= columnCount; ++i) {
			String key = getColumnKey(JdbcUtils.lookupColumnName(rsmd, i));
			Object value = getColumnValue(rs, i);
			jsMap.put(key, value);
		}
		return jsMap;
	}
	
	protected String getColumnKey(String columnName) {
		return this.openCamelCase 
				? JStringUtils.toCamelCase(columnName, this.separator) : columnName;
	}
	
	protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
		Object value = JdbcUtils.getResultSetValue(rs, index);
		int type = rs.getMetaData().getColumnType(index);
		if(type == Types.TINYINT 
				|| (type == Types.BIT && value instanceof Boolean)) {
			value = rs.getInt(index);
		}
		return value;
	}

}
